<template>
  <div class="pagination-container flex-end">
    <el-pagination
      :page-size.sync="pageData.pageSize"
      :total="pageData.total"
      :current-page.sync="pageData.page"
      :background="config.background"
      :layout="config.layout"
      :page-sizes="config.pageSizes"
      class="default"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { scrollTo } from '@/utils/scroll-to'

export default {
  name: 'Pagination',
  props: {
    pageData: {
      type: Object,
      default: function() {
        return {
          total: 20,
          page: 1,
          pageSize: 20
        }
      }
    },
    pageConfig: {
      type: Object,
      default: () => ({
        pageSizes: [10,
          20,
          30,
          50],
        layout: 'total, sizes, prev, pager, next',
        background: true,
        autoScroll: false
      })
    }
  },
  data() {
    return {
      upDataFlag: true,
      timeId: ''
    }
  },
  computed: {
    config() {
      const config = { ...this.pageConfig }
      const keys = Object.keys(config)
      if (!keys.includes('pageSizes')) {
        config.pageSizes = [10,
          20,
          30,
          50]
      }
      if (!keys.includes('layout')) config.layout = 'total, sizes, prev, pager, next'
      if (!keys.includes('background')) config.background = true
      return config
    }
  },
  methods: {
    handleSizeChange(val) {
      console.log(val)
      this.pageData.pageSize = val
      this.triggereUpData()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.pageData.page = val
      this.triggereUpData()
    },
    // 一段时间内唯一触发数据更新，以最后一次的为准 防抖
    triggereUpData() {
      const updata = () => {
        this.timeId = setTimeout(() => {
          this.$emit('pagination')
          if (this.config.autoScroll) {
            scrollTo(0, 800)
          }
          this.upDataFlag = true
          clearTimeout(this.timeId)
        }, 50)
      }
      if (!this.upDataFlag) {
        clearTimeout(this.timeId)
        updata()
        return
      }
      this.upDataFlag = false
      updata()
    }
  }
}
</script>
<style lang="scss" scoped>
.pagination-container {
  background: var(--color-white);
  padding: 10px 0 10px 20px;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active{
  background: var(--color-route-content) !important
}
</style>
